package com.example.lib_common.utils;

import static android.content.Context.ACTIVITY_SERVICE;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.util.Log;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author: njb
 * @date: 2023/8/8 0:03
 * @desc:
 */
public class ToolUtils {
    private static final String TAG = ToolUtils.class.getName();

    /**
     * 打开软件
     *
     * @param packageName 包名
     * @param context     上下文对象
     */
    public static void openApp(String packageName, Activity context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            Intent intent = packageManager.getLaunchIntentForPackage(packageName);
            if (intent != null) {
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
            }
            context.startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
            Log.e(TAG,"跳转App出错"+ e.getMessage());
        }
    }

    public static void openApp(Context context,String packageName){
        try{
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setPackage(packageName);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void openThirdApp(String packageName, Context context) {
        Intent intent = new Intent();
        ComponentName comp = new ComponentName(packageName, "com.example.testmmkv.MainActivity");
        intent.setComponent(comp);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }


    /**
     * 获取前台程序包名
     */
    public static String getForegroundAppPackageName(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Activity.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        return componentInfo.getPackageName();
    }

    /**
     * 根据报名杀死应用
     */
    public static void killApp(Context context, String packageName) {
        try {
            ActivityManager m = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
            Method method = m.getClass().getMethod("forceStopPackage", String.class);
            method.setAccessible(true);
            method.invoke(m, packageName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 杀死第三方应用
     *
     * @param context
     * @param packageName
     */
    public static void killThirdApp(Context context, String packageName) {
        if (packageName != null) {
            killApp(context, packageName);
        }
    }



    /**
     * 获取前台activity名称
     *
     * @param context
     * @return
     */
    public static String getForegroundActivityName(Context context) {
        if (context == null) {
            return "";
        }
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            return cpn.getClassName();
        }
        return "";
    }


    /**
     * 判断APP是否安装了
     *
     * @param packageName 包名
     * @return
     */
    public static boolean isAppInstalled(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();
        try {
            packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }



    public static void unInstall(Context context, String packageName) {
        if (packageName == null) {
            return;
        }
        Uri uri = Uri.parse("package:" + packageName);
        Intent uninstall = new Intent(Intent.ACTION_DELETE, uri);
        uninstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(uninstall);
    }

    /**
     * 静默卸载App
     *
     * @param packageName  包名
     * @return 是否卸载成功
     */
    public static boolean uninstall(String packageName) {
        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder errorMsg = new StringBuilder();
        try {
            process = new ProcessBuilder("pm", "uninstall", packageName).start();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }
        } catch (Exception e) {
            Log.d("e = " , e.toString());
        } finally {
            try {
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (Exception e) {
                Log.d("Exception : " , e.toString());
            }
            if (process != null) {
                process.destroy();
            }
        }
        //如果含有"success"单词则认为卸载成功
        return successMsg.toString().equalsIgnoreCase("success");
    }

    /**
     * 判断应用是否存在
     *
     * @param context     上下文
     * @param packageName 包名
     * @return 是否存在
     */
    private boolean appExist(Context context, String packageName) {
        try {
            List<PackageInfo> packageInfoList = context.getPackageManager().getInstalledPackages(0);
            for (PackageInfo packageInfo : packageInfoList) {
                if (packageInfo.packageName.equalsIgnoreCase(packageName)) {
                    return true;
                }
            }
        } catch (Exception e) {
            Log.d(TAG,e.toString());
        }
        return false;
    }
}
